package com.aneliya.server;

import java.io.IOException;
import java.util.Vector;

import com.aneliya.io.IStreamStrategy;
import com.aneliya.model.Message;

public class ServerSender extends Thread {
	private Vector<Message> messageQueue = new Vector<Message>();
	
	private IStreamStrategy streamStrategy;
	public void setStreamStrategy(IStreamStrategy streamStrategy) {
		this.streamStrategy = streamStrategy;
	}
	
	public synchronized void sendMessage(Message message) {
		messageQueue.add(message);
		notify();		
	}
	
	private synchronized Message getNextMessageFromQueue() throws InterruptedException {
		while (messageQueue.size() == 0) {
			wait();
		}
		Message message = messageQueue.firstElement();
		messageQueue.remove(0);
		return message;
	}
	
	private void sendMessageToServer(Message message) throws IOException {
		streamStrategy.writeMessage(message);
	}
	
	public void run() {
		try {
			while (!isInterrupted()) {
				Message message = getNextMessageFromQueue();
				sendMessageToServer(message);
			}
		} catch (Exception ex) {
			// Communication problem
		}
	}

}
